#!/usr/bin/env python
# -*- coding: utf-8 -*-

import akshare as ak
from pandas.core.interchange.dataframe_protocol import DataFrame

from web.api.base_api import BaseApi
from web.constants.python_api_result import PythonApiResult
from web.manager.log_manager import LogManager
from web.models.macro_china_gdp import MacroChinaGdp

Logger = LogManager.get_logger(__name__)


class MacroDataApi(BaseApi):
    """
    宏观数据api
    """

    def write_gdp_if_none(self):
        """
        保存或更新gdp数据
        """

        # 调用接口获取数据
        macro_china_gdp_df: DataFrame = ak.macro_china_gdp()
        macro_china_gdp_list: list = macro_china_gdp_df.values.tolist()

        if macro_china_gdp_list is not None and len(macro_china_gdp_list) > 0:
            _macro_china_gdp_list: list[MacroChinaGdp] = list()
            for macro_china_gdp_row in macro_china_gdp_list:

                # 判断数据是否已经存在，如果不存在则插入记录
                _macro_china_gdp: MacroChinaGdp = self.macro_china_gdp_service.find_by_quarter(macro_china_gdp_row[0])
                if _macro_china_gdp is None:
                    macro_china_gdp: MacroChinaGdp = MacroChinaGdp()
                    macro_china_gdp.quarter = macro_china_gdp_row[0]
                    macro_china_gdp.gdp_av = macro_china_gdp_row[1]
                    macro_china_gdp.gdp_yoyg = macro_china_gdp_row[2]
                    macro_china_gdp.primary_industry_av = macro_china_gdp_row[3]
                    macro_china_gdp.primary_industry_yoyg = macro_china_gdp_row[4]
                    macro_china_gdp.secondary_industry_av = macro_china_gdp_row[5]
                    macro_china_gdp.secondary_industry_yoyg = macro_china_gdp_row[6]
                    macro_china_gdp.tertiary_industry_av = macro_china_gdp_row[7]
                    macro_china_gdp.tertiary_industry_yoyg = macro_china_gdp_row[8]
                    _macro_china_gdp_list.append(macro_china_gdp)
            self.macro_china_gdp_service.batch_insert(_macro_china_gdp_list)
        print(PythonApiResult.FINISH)